//content js is used to interact with the webpage that opened.

console.log("Content script is loaded");

chrome.runtime.sendMessage({action:"getData",},(response)=>{
    console.log("Received from background:",response.data)   
})

chrome.runtime.onMessage.addListener((request,sender,sendResponse)=>{
    
    console.log("extension internal message")

    if(request.action === 'changeColor'){
        document.body.style.backgroundColor = "lightblue";
    }
    else if(request.action === 'clickbutton'){
        function clickMore(){
            const anchors= document.querySelectorAll("a");
            const arr = Array.from(anchors)
            const moreBtn = arr.filter((e)=>e.textContent.includes("更多")).pop();
            moreBtn && moreBtn.click()
            setTimeout(()=>{
                window.history.back();
            },2000)
        }
        var condition = true;
        while(condition){
            condition = false;
            clickMore()
            setTimeout(() => {
                condition = true
            }, 3000);  
        }
    }else if(request.action === 'myLoopAction'){
        console.log("received message from background")
        const loop = ()=>{
            setTimeout(()=>{
                //TODO: replace here to do some dom action 
                const r = (Math.random()*255+1)%255
                const g = (Math.random()*255+1)%255
                const b = (Math.random()*255+1)%255
                const a = (Math.random()*255+1)%255
                document.body.style.backgroundColor = `rgba(${r},${g},${b},${a})`
                loop();
            },2000)
        }
        loop();
    }
})